package com.ns.core.utils.sg;

import com.ns.core.current.config.SymbolsMark;
import io.minio.http.Method;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 最nb的工具类
 *
 * @author lw
 */
public class NbUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(NbUtil.class);

    /**
     * 该字符串是否为null或者空串
     */
    public static boolean isNull(String str) {
        return (str == null || str.equals(""));
    }

    /**
     * 指定字符串是否含有null或者空串
     */
    public static boolean hasNull(String... str) {
        for (String string : str) {
            if ((string == null || string.isEmpty())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 如果一个字符串为(null,"","null")，则转化为指定值
     */
    public static String toStr(String str, String toStr) {
        if (str == null || str.equals(SymbolsMark.EMPTY) || str.equals(SymbolsMark.NULL)) {
            return toStr;
        }
        return str;
    }

    /**
     * 如果该货不能转成一个数字，则返回指定值
     */
    public static Integer toInt(String str, Integer toInt) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return toInt;
        }
    }

    private static final Pattern patternNumberPattern = Pattern.compile("[0-9]*");

    /**
     * 验证一个str是否为数字
     *
     * @param str 参数
     * @return boolean
     */
    public static boolean isNumber(String str) {
        return patternNumberPattern.matcher(str).matches();
    }

    private static final Pattern patternNumberPhone = Pattern.compile("[1]\\d{10}");

    /**
     * 验证一个str是否为手机号
     *
     * @param str 参数
     * @return boolean
     */
    public static boolean isPhone(String str) {
        if (str == null) {
            return false;
        }
        return patternNumberPhone.matcher(str).matches();
    }

    /**
     * 判断一个数是否在0、1、2、3...10、20、30...100、200、300... 数列里面
     */
    private static final Pattern patternSeries = Pattern.compile("[0-9]0*");

    public static boolean isSeries(int num) {
        return patternSeries.matcher(num + "").matches();
    }


    /**
     * 将一个字符串ISO-8859-1转码UTF-8
     */
    public static String toUtf8(String str) {
        return new String(str.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
    }

    /**
     * 将字符串转化为指定数据类型
     */
    @SuppressWarnings("unchecked")
    public static <T> T getObjectByClass(String str, Class<T> cs) {
        Object value;
        if (str == null) {
            value = null;
        } else if (cs.equals(String.class)) {
            value = str;
        } else if (cs.equals(int.class) || cs.equals(Integer.class)) {
            value = Integer.parseInt(str);
        } else if (cs.equals(long.class) || cs.equals(Long.class)) {
            value = Long.parseLong(str);
        } else if (cs.equals(short.class) || cs.equals(Short.class)) {
            value = Short.parseShort(str);
        } else if (cs.equals(float.class) || cs.equals(Float.class)) {
            value = Float.parseFloat(str);
        } else if (cs.equals(double.class) || cs.equals(Double.class)) {
            value = Double.parseDouble(str);
        } else if (cs.equals(boolean.class) || cs.equals(Boolean.class)) {
            value = Boolean.parseBoolean(str);
        } else {
            throw new RuntimeException("超纲的类型：" + cs + "，未能转换值：" + str);
        }
        return (T) value;
    }

    /**
     * 返回随机数
     */
    public static int getRandom(int min, int max) {
        max = max + 1;
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

    /**
     * 返回随机字符串
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 返回唯一标示28位唯一标示符
     */
    public static String getMarking28() {
        return System.currentTimeMillis() + "" + new Random().nextInt(Integer.MAX_VALUE);
    }

    /**
     * 取文件后缀
     */
    public static String getSuffixName(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    /**
     * 指定Properties配置文件，读取成为Map, 返回null代表无此配置文件
     */
    public static Map<String, String> readPropToMap(String propertiesPath) {
        Map<String, String> map = new HashMap<>();
        try {
            InputStream is = NbUtil.class.getClassLoader().getResourceAsStream(propertiesPath);
            if (is == null) {
                return Collections.emptyMap();
            }
            Properties prop = new Properties();
            prop.load(is);
            for (String key : prop.stringPropertyNames()) {
                map.put(key, prop.getProperty(key));
            }
        } catch (IOException e) {
            throw new RuntimeException("配置文件(" + propertiesPath + ")加载失败", e);
        }
        return map;
    }


    /**
     * 初始化对象的属性，根据Map，支持直接为类static字段赋值
     */
    public static Object initPropByMap(Map<String, String> map, Object obj) {
        Class<?> cs = null;
        if (obj instanceof Class) {
            // 已经是类
            cs = (Class<?>) obj;
            obj = null;
        } else {
            // 实例对象
            cs = obj.getClass();
        }

        for (Field field : cs.getDeclaredFields()) {
            String value = map.get(field.getName());
            if (value == null) {
                // 为空代表没配置此项
                continue;
            }
            try {
                Object valueConvert = getObjectByClass(value, field.getType());
                field.set(obj, valueConvert);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new RuntimeException("属性取值出错：" + field.getName(), e);
            }
        }
        return obj;
    }

    /**
     * 返回一个6位数手机验证码
     */
    public static String getMobileCode() {
        return Double.toString(((Math.random() * 9 + 1) * 100000)).substring(0, 6);
    }


    /**
     * 将一个request请求Header所携带的参数封装成map返回
     */
    public static Map<String, String> getHeaderMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        try {
            // 获得K列表
            Enumeration<String> paramNames = request.getHeaderNames();
            request.setCharacterEncoding(StandardCharsets.UTF_8.name());
            while (paramNames.hasMoreElements()) {
                // 获得k
                String key = paramNames.nextElement();
                // 获得v
                String value = request.getHeader(key);
                if (request.getMethod().equals(Method.GET.name())) {
                    new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                }
                map.put(key, value);
            }
        } catch (Exception e1) {
            LOGGER.error(e1.getMessage());
        }
        return map;
    }


}
